//
//  DailyDietViewController.m
//  SHHCPhone
//
//  Created by gfsh on 14-6-18.
//  Copyright (c) 2014年 sheng long. All rights reserved.
//

#import "DailyDietViewController.h"
#import "DailyDietDetailViewController.h"
#import "DailyDietView.h"
#import "DailyDietInfo.h"

#define DAILYDIET @"DailyDiet"
#define DAILYKEY(index) [NSString stringWithFormat:@"%@_%d",DAILYDIET,index]
#define IS_MATERIAL(flag) flag?@"true":@"false"

@interface DailyDietViewController ()<DailyDietViewDelegate>

@end

@implementation DailyDietViewController
{
    DailyDietView *ddv;
    NSInteger selectedIndex;
    NSDictionary *meals;
    NSArray *mealKeys;
    NSIndexPath *tempIP;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    mealKeys = @[kBreakfast,kLaunch,kDinner,kBreakfastSnack,kLaunchSnack,kDinnerSnack];
    meals = @{kBreakfast:kBreakfastValue,kLaunch:kLaunchValue,kDinner:kDinnerValue,kBreakfastSnack:kBreakfastSnackValue,kLaunchSnack:kLaunchSnackValue,kDinnerSnack:kDinnerSnackValue};
    
    [self initContentView];
}

-(void)viewWillAppear:(BOOL)animated
{
    for (UIView *view in navigationBarView.subviews) {
        [view removeFromSuperview];
    }
    navigationBarView.title = @"每日食谱推荐";
    [self showNavbarStyle];
}

#pragma mark 初始化内容
- (void)initContentView
{
    ddv = [[DailyDietView alloc]initWithFrame:CGRectMake(0, NAVIGATIONBAR_HEIGHT, CURRENT_CONTENT_WIDTH, CURRENT_CONTENT_HEIGHT-NAVIGATIONBAR_HEIGHT)];
    ddv.delegate = self;
    [self.view addSubview:ddv];
    [ddv tagLeftBtnClick];
}

#pragma mark dailyDietView delegate

- (void)cellClick:(id)obj
{
    DietInfo *di = (DietInfo*)obj;
    if (di.dish) {
        if (di.foodDetail||di.amount||di.energy||di.protein||di.fat||di.CHO||di.method) {
            DailyDietDetailViewController *dddvc = [[DailyDietDetailViewController alloc]initWithDietInfo:di];
            [self.navigationController pushViewController:dddvc animated:YES];
        }else{
            [LoadingFrameView autoDisappearBlockingview:@"暂无营养标签"];
        }
    }
}

- (void)refreshFood:(id)obj
{
    if (obj) {
        tempIP = (NSIndexPath*)obj;
        DailyDietInfo *ddi = ddv.data[tempIP.section];
        DietInfo *di = ddi.dietInfos[tempIP.row];
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:1];
        [dic setValue:IOS_RECIPECHANGEONE forKeyPath:IOS_METHOD_NAME];
        [dic setValue:APP_USER_MSG.id forKeyPath:kUserID];
        [dic setValue:IS_MATERIAL(selectedIndex) forKey:kIsMaterial];
        [dic setValue:di.foodID forKey:kFood_ID];
        [dic setValue:di.weight forKey:kFood_Weight];
        [dic setValue:di.mealIndex forKey:kFood_Mark];
        
        [self loadData:dic tag:IOS_RECIPECHANGEONE_TAG];
    }
}

- (void)leftBtnClick
{
    selectedIndex = 0;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:1];
    [dic setValue:IOS_RECIPERECOMMEND forKeyPath:IOS_METHOD_NAME];
    [dic setValue:APP_USER_MSG.id forKeyPath:kUserID];
    [dic setValue:IS_MATERIAL(selectedIndex) forKey:kIsMaterial];

    [self loadData:dic tag:IOS_RECIPERECOMMEND_TAG];

}

- (void)rightBtnClick
{
    selectedIndex = 1;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:1];
    [dic setValue:IOS_RECIPECHANGEGROUP forKeyPath:IOS_METHOD_NAME];
    [dic setValue:APP_USER_MSG.id forKeyPath:kUserID];
    [dic setValue: IS_MATERIAL(selectedIndex) forKey:kIsMaterial];
    
    [self loadData:dic tag:IOS_RECIPERECOMMEND_TAG];
}

- (void)changeFoodBtnClick
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:1];
    [dic setValue:IOS_RECIPERECOMMEND forKeyPath:IOS_METHOD_NAME];
    [dic setValue:APP_USER_MSG.id forKeyPath:kUserID];
    [dic setValue:IS_MATERIAL(selectedIndex) forKey:kIsMaterial];
    
    [self loadData:dic tag:IOS_RECIPECHANGEGROUP_TAG];
}

#pragma mark 加载数据
-(void)loadData:(NSDictionary*)params tag:(NSInteger)tag
{
    CLog(@"获取菜品或者食材");
    [LoadingFrameView showLoadingview];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSData *cache = [userDefaults dataForKey:DAILYKEY(selectedIndex)];
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:cache];
    NSArray *cacheArr = (NSArray*)[unarchiver decodeObjectForKey:@"cache"];
    if (CURRENT_NETWORK_STATE&&((tag==IOS_RECIPERECOMMEND_TAG&&!cacheArr)||(tag!=IOS_RECIPERECOMMEND_TAG))) {
        ASIHTTPRequest *request =  [NetUtls httpGet:self withValue:params tag:tag need:YES];
        [request startAsynchronous];
    }else{
        [LoadingFrameView directlyDisappear];
        ddv.data = cacheArr;
    }
}

-(void)requestFinished:(ASIHTTPRequest *)request
{
    CLog(@"%@",[[NSString alloc]initWithData:request.responseData encoding:NSUTF8StringEncoding]);
    NSDictionary *dic = [[[NSString alloc]initWithData:request.responseData encoding:NSUTF8StringEncoding]objectFromJSONString];//[[request responseString] objectFromJSONString];
    
    if (dic[@"error"]) {
        [LoadingFrameView autoDisappearBlockingview:@"获取失败"];
        return;
    }
    [LoadingFrameView autoDisappearBlockingview:@"获取成功"];
    
    //获取菜品 获取食材
    if (request.tag == IOS_RECIPERECOMMEND_TAG) {
        if (dic != nil) {
            [LoadingFrameView directlyDisappear];
            [self transformRequestResult:dic];
        }else{
            [self requestFailed:request];
        }
    }
    
    //换一组
    if (request.tag == IOS_RECIPECHANGEGROUP_TAG) {
        if (dic != nil) {
            [LoadingFrameView directlyDisappear];
            [self transformRequestResult:dic];
        }else{
            [self requestFailed:request];
        }
    }
    
    //换一个
    if (request.tag == IOS_RECIPECHANGEONE_TAG) {
        if (dic != nil) {
            [LoadingFrameView directlyDisappear];
            DailyDietInfo *ddi = ddv.data[tempIP.section];
            DietInfo *di = ddi.dietInfos[tempIP.row];
            di.foodID = [self objToString:[dic objectForKey:kFoodID]];
            di.foodName = [self objToString:[dic objectForKey:kFoodName]];
            di.foodDetail = [self objToString:[dic objectForKey:kFoodSummer]];
            di.picPath = [self objToString:[dic objectForKey:kFoodPicPath]];
            di.content = [self objToString:[dic objectForKey:kFoodContent]];
            di.weight = [self objToString:[dic objectForKey:kFoodWeight]];
            di.amount = [self objToString:[dic objectForKey:kFoodAmount]];
            di.energy = [self objToString:[dic objectForKey:kFoodEnergy]];
            di.protein = [self objToString:[dic objectForKey:kFoodProtein]];
            di.fat = [self objToString:[dic objectForKey:kFoodFat]];
            di.CHO = [self objToString:[dic objectForKey:kFoodCHO]];
            di.calory100 = [self objToString:[dic objectForKey:kFoodCalory100]];
            di.method = [self objToString:[dic objectForKey:kFoodMethod]];
            [ddv refreshCell:tempIP];
            
        }else{
            [self requestFailed:request];
        }
    }
}

-(void)requestFailed:(ASIHTTPRequest *)request
{
//    if (request.tag == IOS_RECIPERECOMMEND_TAG) {
//        [LoadingFrameView autoDisappearBlockingview:[NSString stringWithFormat:@"获取%d失败",IOS_RECIPERECOMMEND_TAG]];
//    }else{
        [LoadingFrameView autoDisappearBlockingview:@"获取失败"];
//    }
}

- (void)transformRequestResult:(NSDictionary*)dic
{
    DailyDietInfo *breakfast = [self dailyDietInfoFrom:dic dietType:kBreakfast];
    DailyDietInfo *breakfastSnack = [self dailyDietInfoFrom:dic dietType:kBreakfastSnack];
    DailyDietInfo *launch = [self dailyDietInfoFrom:dic dietType:kLaunch];
    DailyDietInfo *launchSnack = [self dailyDietInfoFrom:dic dietType:kLaunchSnack];
    DailyDietInfo *dinner = [self dailyDietInfoFrom:dic dietType:kDinner];
    DailyDietInfo *dinnerSnack = [self dailyDietInfoFrom:dic dietType:kDinnerSnack];
    NSMutableArray *tArr = [NSMutableArray array];
//    NSArray *keys = [dic allKeys];
//    for (NSString *key in keys) {
//        DailyDietInfo *ddi = [self dailyDietInfoFrom:dic dietType:key];
//        if (ddi) {
//            [tArr addObject:ddi];
//        }
//    }
    if (breakfast) {
        [tArr addObject:breakfast];
    }
    if (breakfastSnack) {
        [tArr addObject:breakfastSnack];
    }
    if (launch) {
        [tArr addObject:launch];
    }
    if (launchSnack) {
        [tArr addObject:launchSnack];
    }
    if (dinner) {
        [tArr addObject:dinner];
    }
    if (dinnerSnack) {
        [tArr addObject:dinnerSnack];
    }
    
    ddv.data = tArr;
    
    // 归档操作(将归档数据写入NSMutableData中，然后将NSMutableData对象写成文件)
    NSMutableData *data = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    // 写入数据
    [archiver encodeObject:ddv.data forKey:@"cache"];
    // 写入完毕
    [archiver finishEncoding];

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:data forKey:DAILYKEY(selectedIndex)];
    [userDefaults synchronize];
}

- (DailyDietInfo*)dailyDietInfoFrom:(NSDictionary*)dic dietType:(NSString*)type
{
    NSArray *items = [dic objectForKey:type];
    if (!items) {
        return nil;
    }
    DailyDietInfo *ddi = [[DailyDietInfo alloc]init];
    ddi.mealName = [meals objectForKey:type];
    ddi.isFold = [type isEqualToString:kBreakfast]?NO:YES;
    NSInteger index = [mealKeys indexOfObject:type]+1;
    NSMutableArray *tempArr = [NSMutableArray array];
    for (NSDictionary *foodInfo in items) {
        DietInfo *di = [[DietInfo alloc]init];
        di.foodID = [self objToString:[foodInfo objectForKey:kFoodID]];
        di.foodName = [self objToString:[foodInfo objectForKey:kFoodName]];
        di.foodDetail = [self objToString:[foodInfo objectForKey:kFoodSummer]];
        di.picPath = [self objToString:[foodInfo objectForKey:kFoodPicPath]];
        di.content = [self objToString:[foodInfo objectForKey:kFoodContent]];
        di.weight = [self objToString:[foodInfo objectForKey:kFoodWeight]];
        di.amount = [self objToString:[foodInfo objectForKey:kFoodAmount]];
        di.energy = [self objToString:[foodInfo objectForKey:kFoodEnergy]];
        di.protein = [self objToString:[foodInfo objectForKey:kFoodProtein]];
        di.fat = [self objToString:[foodInfo objectForKey:kFoodFat]];
        di.CHO = [self objToString:[foodInfo objectForKey:kFoodCHO]];
        di.calory100 = [self objToString:[foodInfo objectForKey:kFoodCalory100]];
        di.method = [self objToString:[foodInfo objectForKey:kFoodMethod]];
        di.dish = !selectedIndex;
        di.mealIndex = [NSString stringWithFormat:@"%d",index];
        [tempArr addObject:di];
    }
    ddi.dietInfos = tempArr;
    return ddi;
}

- (NSString*)objToString:(id)obj
{
    if ((NSNull*)obj == [NSNull null]) {
        return nil;
    }
    
    return obj?[NSString stringWithFormat:@"%@",obj]:nil;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];

}

@end
